import re
import requests
import oss2
import time
import traceback
import json
import redis
from rpa import rpa_server
from public import *
from tools import *
mlog = MyLogger("task")
class Executor(object):
    def __init__(self):
        self.rpa = rpa_server()
    
    def check_is_stop(self):
        """_summary_
        """
        is_stop = redis_client.safe_get(REDIS_STOP_KEY)
        return int(is_stop or 0)

    def get_task_info(self):
        # 先读取有没有正在执行的task
        running_task = redis_client.safe_get(REDIS_RUNNING_TASK_KEY)
        if running_task:
            return running_task
        # 从任务列表里读取
        task = redis_client.safe_lpop(REDIS_TASK_LIST_KEY)
        # 设置running task
        if task:
            redis_client.safe_set(REDIS_RUNNING_TASK_KEY,task)
        return task
    
    def add_task_back_to_list(self,task):
        redis_client.safe_rpush(REDIS_TASK_LIST_KEY,task)
        return True

    def clear_running_task(self):
        redis_client.safe_delete(REDIS_RUNNING_TASK_KEY)
        return True

    def upload_file_to_oss(self,file):
        # file : D:\project\zmn_aiprd_project\file\download\BIZ_5023736_产品方案_20250124.docx
        auth = oss2.Auth('LTAI5tLoYggocBbMJHHQMNF2', 'MTA8JKke9hjXeT25mu8dVzhKrm6141')
        bucket = oss2.Bucket(auth, "https://oss-cn-beijing.aliyuncs.com", 'zmn-bigdata')

        local_file_path = file
        filename = file.split("\\")[-1]
        oss_file_path = f"aidoc/{filename}"

        # # 上传文件
        r = bucket.put_object_from_file(oss_file_path, local_file_path)
        url = bucket.sign_url('GET',oss_file_path,3600)
        return url

    def post_better_yeah_api(self,prd_link,prd_level):
        access_key = "NjNhMmE5MmM4MTQ2MmUxYjY4Njc2YWUwLDExNTAsMTcxNTM5NTI3Nzk5MQ=="

        url = "https://ai-api.betteryeah.com/v1/public_api/rest_api/0e182c93967046c7a050376e31599d74/execute_flow"
        data = {
            "inputs":{
            "prd_link":prd_link,
            "prd_level":prd_level
            }
        }
        
        headers = {
            "Content-Type":"application/json",
            "Access-Key":access_key,
            "Workspace-Id":"63a2a92c81462e1b68676ae0"
        }

        res = requests.post(url,data=json.dumps(data),headers=headers)
        text = re.findall("```json([\s\S]*?)```",res.text)[0].replace('\\n','').replace('\\','').strip()
        res_data = json.loads(text.strip())
        return res_data

    def callback_devops(self,request_id,callback_url,res_data,res_msg,log_msg):
        mlog.info("===========回调devopss==========")
        mlog.info(f"===========[{request_id}][{log_msg}]==========")
        # print(res_data)
        with open(f"{request_id}.txt","w",encoding="utf-8") as fp:
            fp.write(json.dumps(res_data,ensure_ascii=False))

        total_score = round(sum([_["指标评分"] for _ in res_data["详细"]]) / len(res_data["详细"]),2)
        final_data = {
            "request_id":request_id,
            "total_score":total_score,
            "data":[
                {
                    "item":_["指标名称"],
                    "item_score":int(_["指标评分"]),
                    "score_basis":_["评分理由"]
                } for _ in res_data["详细"]
            ],
            "status":200 if res_msg == "成功" else 400,
            "msg":res_msg
        }
        print(json.dumps(final_data,ensure_ascii=False))
        for i in range(10):
            try:
                url = callback_url
                res = requests.post(url, data=json.dumps(final_data))
                print(res.text)
                print(res.status_code)
                if res.status_code == 200:
                    break
            except Exception as e:
                mlog.error(f"回调devops接口异常:[{request_id}][{callback_url}][{str(e)}]")
                time.sleep(10)

    def execute_task(self,task):
        """_summary_

        Args:
            task (_type_): _description_
        """
        task = json.loads(task)
        request_id = task["request_id"]
        check_type = task["check_type"]

        check_name = {
            10:"关键词搜索",
            20:"产品方案检测",
            30:"系统架构方案检测",
            31:"系统详细设计方案检测"
        }.get(check_type)
        if check_type != 20:
            res_data = f"暂不支持检测:{check_type}-{check_name}"
            log_msg = res_data
        else:
            mlog.info("获取到task")
            mlog.info(task)
            callback_url = task["callback_url"]
            dingding_doc_link = task["dingding_doc_link"]
            level = task["level"]

            mlog.info("获取到prd")
            # 1.下载文件
            local_file = self.rpa.run(dingding_doc_link)
            mlog.info(f"文件已下载:[{local_file}]")
            # 2.上传到oss
            oss_file = self.upload_file_to_oss(local_file)
            mlog.info(f"文件已上传:[{oss_file}]")
            # 3.调起斑头雁
            res_data = self.post_better_yeah_api(oss_file,level)
            mlog.info('斑头雁已调起')   
            log_msg = "成功返回检测结果"
            # 4.回调devops
            self.callback_devops(request_id,callback_url,res_data,"成功",log_msg)

    def run(self):
        while True:
            if (s:=self.check_is_stop()) == -1:
                mlog.info(f"暂停点获取:[{s}]")
                break
            time.sleep(s)
            task = self.get_task_info()
            print("获取到任务:",task)
            if task:
                mlog.info("获取到task:")
                mlog.info(task)
                try:
                    self.execute_task(task)
                except Exception as e:
                    mlog.error("程序异常！")
                    mlog.error(traceback.format_exc())
                    task = json.loads(task)
                    retry_times = task.get("retry_times") or 0
                    retry_times += 1
                    if retry_times <= 3:
                        self.add_task_back_to_list(json.dumps(task,ensure_ascii=False))
                        mlog.info("任务已重新添加到任务列表")
                    else:
                        mlog.info("执行异常异常超过三次")
                        # 4.回调devops
                        request_id = task["request_id"]
                        callback_url = task["callback_url"]
                        self.callback_devops(request_id,callback_url,str(e),res_msg="执行异常异常超过三次",log_msg="异常超过三次,返回devops")
                finally:
                    self.clear_running_task()
            time.sleep(10)

if __name__ == "__main__":
    e = Executor()
    e.run()